package cn.edu.zut.soft.graduate.base.excel;

import cn.edu.zut.soft.basic.core.util.DateTimeUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;

/**
 * Created by chuchuang on 16/9/15.
 */
public class ExcelReader {
    protected static final String dateTimeFmtPattern = "yyyy-MM-dd HH:mm:ss";

    protected static final String dateFmtPattern = "yyyy-MM-dd";

    protected static final DataFormatter formatter = new DataFormatter();

    /**
     * 读取excel文件（同时支持2003和2007格式）
     *
     * @param fileName 文件名，绝对路径
     * @return list中的map的key是列的序号
     * @throws Exception io异常等
     */
    public static List<Map<String, String>> readExcel(String fileName) throws Exception {
        FileInputStream fis = null;
        List<Map<String, String>> list = null;
        try {
            String extension = FilenameUtils.getExtension(fileName);

            fis = new FileInputStream(fileName);
            list = read(fis, extension);

            return list;
        } finally {
            if (null != fis) {
                fis.close();
            }
        }

    }

    /**
     * 读取excel文件（同时支持2003和2007格式）
     *
     * @param fis       文件输入流
     * @param extension 文件名扩展名: xls 或 xlsx 不区分大小写
     * @return list中的map的key是列的序号
     * @throws Exception io异常等
     */
    public static List<Map<String, String>> read(InputStream fis, String extension) throws Exception {

        Workbook wb = null;
        List<Map<String, String>> list = null;
        try {

            if ("xls".equalsIgnoreCase(extension)) {
                wb = new HSSFWorkbook(fis);
            } else if ("xlsx".equalsIgnoreCase(extension)) {
                wb = new XSSFWorkbook(fis);
            } else {
                throw new Exception("file is not office excel");
            }

            list = readWorkbook(wb);

            return list;

        } finally {
//            if (null != wb) {
//                wb.close();
//            }
            if (null != fis) {
                fis.close();
            }
        }

    }

    protected static List<Map<String, String>> readWorkbook(Workbook wb) throws Exception {
        List<Map<String, String>> list = new LinkedList<Map<String, String>>();

        for (int k = 0; k < wb.getNumberOfSheets(); k++) {
            Sheet sheet = wb.getSheetAt(k);
            int rows = sheet.getPhysicalNumberOfRows();

            for (int r = 0; r < rows; r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                Map<String, String> map = new HashMap<String, String>();
                int cells = row.getPhysicalNumberOfCells();

                for (int c = 0; c < cells; c++) {
                    Cell cell = row.getCell(c);
                    if (cell == null) {
                        continue;
                    }
                    String value = getCellValue(cell);
                    map.put(String.valueOf(cell.getColumnIndex() + 1), value);
                }
                list.add(map);
            }

        }

        return list;
    }

    protected static String getCellValue(Cell cell) {
        String value = null;

        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_FORMULA: // 公式
            case Cell.CELL_TYPE_NUMERIC: // 数字
                double doubleVal = cell.getNumericCellValue();
                short format = cell.getCellStyle().getDataFormat();
                String formatString = cell.getCellStyle().getDataFormatString();

                if (format == 14 || format == 31 || format == 57 || format == 58 || (format >= 176 && format <= 183)) {
                    // 日期
                    Date date = DateUtil.getJavaDate(doubleVal);
                    value = formatDate(date, dateFmtPattern);
                } else if (format == 20 || format == 32 || (format >= 184 && format <= 187)) {
                    // 时间
                    Date date = DateUtil.getJavaDate(doubleVal);
                    value = formatDate(date, "HH:mm");
                } else {
                    value = String.valueOf(doubleVal);
                }

                break;
            case Cell.CELL_TYPE_STRING: // 字符串
                value = cell.getStringCellValue();

                break;
            case Cell.CELL_TYPE_BLANK: // 空白
                value = "";
                break;
            case Cell.CELL_TYPE_BOOLEAN: // Boolean
                value = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_ERROR: // Error，返回错误码
                value = String.valueOf(cell.getErrorCellValue());
                break;
            default:
                value = "";
                break;
        }
        return value;
    }

    private static String formatDate(Date d, String sdf) {
        String value = null;

        if (d.getTime() == 0) {
            value = DateTimeUtil.getFormatDate(d, dateFmtPattern);
        } else {
            value = DateTimeUtil.getFormatDate(d, sdf);
        }
        return value;
    }


}
